import { readWords, readRecords, writeRecords, generateId } from './data';
import { Word, Question, ChallengeRecord, QuestionType } from '@/types';

function createMaskedWord(english: string): string | null {
  if (!english || english.length < 2) return null;
  const chars = english.split('');
  const maskableIndexes = chars
    .map((ch, idx) => ({ ch, idx }))
    .filter(({ ch, idx }) => /[a-zA-Z]/.test(ch) && idx !== 0 && idx !== chars.length - 1)
    .map(({ idx }) => idx);

  if (maskableIndexes.length === 0) {
    return null;
  }

  const maskCount = Math.min(3, Math.max(1, Math.floor(maskableIndexes.length / 2) || 1));
  const shuffled = [...maskableIndexes].sort(() => Math.random() - 0.5);
  for (let i = 0; i < maskCount && i < shuffled.length; i++) {
    const index = shuffled[i];
    chars[index] = '_';
  }

  return chars.join('');
}

// 获取分类下的所有单词（包括子分类）
export function getWordsInCategory(categoryId: string, allWords: Word[], allCategories: any[]): Word[] {
  // 获取该分类及其所有子分类的ID
  const categoryIds = [categoryId];
  const findChildren = (parentId: string) => {
    allCategories.forEach(cat => {
      if (cat.parentId === parentId) {
        categoryIds.push(cat.id);
        findChildren(cat.id);
      }
    });
  };
  findChildren(categoryId);

  return allWords.filter(word => categoryIds.includes(word.categoryId));
}

// 生成挑战题目
export function generateChallenge(categoryId: string, allWords: Word[], allCategories: any[], options?: { fillOnly?: boolean }): Question[] {
  const words = getWordsInCategory(categoryId, allWords, allCategories);
  
  if (words.length < 4) {
    throw new Error('该分类下单词数量不足，至少需要4个单词');
  }

  const questions: Question[] = [];
  const selectedWords = [...words].sort(() => Math.random() - 0.5);

  // 纯填空模式：仅生成10道可遮挡的英文单词
  if (options?.fillOnly) {
    const maskable = selectedWords.filter(w => !!createMaskedWord(w.english));
    if (maskable.length < 4) {
      throw new Error('该分类下可用于拼写题的单词不足，至少需要4个单词');
    }
    maskable.slice(0, 10).forEach(word => {
      const masked = createMaskedWord(word.english)!;
      questions.push({
        wordId: word.id,
        type: 'fill-in',
        question: word.chinese,
        correctAnswer: word.english,
        maskedWord: masked,
      });
    });
    return questions;
  }

  selectedWords.slice(0, 10).forEach(word => {
    const typeRoll: QuestionType[] = ['en-to-cn', 'cn-to-en', 'fill-in'];
    const type = typeRoll[Math.floor(Math.random() * typeRoll.length)];

    if (type === 'fill-in') {
      const masked = createMaskedWord(word.english);
      if (masked) {
        questions.push({
          wordId: word.id,
          type,
          question: word.chinese,
          correctAnswer: word.english,
          maskedWord: masked,
        });
        return;
      }
    }

    // 默认生成选择题
    const mcType: QuestionType = type === 'fill-in' ? (Math.random() > 0.5 ? 'en-to-cn' : 'cn-to-en') : type;
    
    // 生成选项（3个错误选项 + 1个正确答案）
    const wrongWords = words
      .filter(w => w.id !== word.id)
      .sort(() => Math.random() - 0.5)
      .slice(0, 3);
    
    const correctText = mcType === 'en-to-cn' ? word.chinese : word.english;
    const pool = words
      .filter(w => w.id !== word.id)
      .map(w => (mcType === 'en-to-cn' ? w.chinese : w.english))
      .filter(txt => txt !== correctText);

    const uniqueWrong = new Set<string>();
    wrongWords.forEach(w => {
      const txt = mcType === 'en-to-cn' ? w.chinese : w.english;
      if (txt !== correctText) uniqueWrong.add(txt);
    });

    const shuffledPool = [...pool].sort(() => Math.random() - 0.5);
    for (const txt of shuffledPool) {
      if (uniqueWrong.size >= 3) break;
      uniqueWrong.add(txt);
    }

    if (uniqueWrong.size < 3) {
      return;
    }

    const options = [correctText, ...Array.from(uniqueWrong).slice(0, 3)];
    options.sort(() => Math.random() - 0.5);
    
    questions.push({
      wordId: word.id,
      type: mcType,
      question: mcType === 'en-to-cn' ? word.english : word.chinese,
      options,
      correctAnswer: mcType === 'en-to-cn' ? word.chinese : word.english,
    });
  });

  return questions;
}

// 提交挑战结果
export function submitChallenge(
  userId: string,
  categoryId: string,
  questions: Question[],
  userAnswers: string[],
  timeSpent: number
): ChallengeRecord {
  // 计算得分
  let score = 0;
  questions.forEach((q, index) => {
    q.userAnswer = userAnswers[index];
    q.isCorrect = q.userAnswer === q.correctAnswer;
    if (q.isCorrect) score++;
  });

  // 计算积分：得分 * 100 - 耗时
  const points = Math.max(0, score * 100 - timeSpent);

  const record: ChallengeRecord = {
    id: generateId(),
    userId,
    categoryId,
    questions,
    score,
    timeSpent,
    points,
    createdAt: new Date().toISOString(),
  };

  const records = readRecords();
  records.push(record);
  writeRecords(records);

  return record;
}

